﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Core;
using SmartSpace;
using SmartSpace.Packaging;
using System.IO;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.core
{
    public partial class org_list : System.Web.UI.Page
    {
        private Guid _selectedId;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                _selectedId = new Guid(Request.QueryString["id"]);
            }

            if (_selectedId != Guid.Empty)
            {
                _ctlLinkAdd.NavigateUrl = string.Format("./org-add.aspx?id={0}", _selectedId);
                _ctlLinkAssign.NavigateUrl = string.Format("./org-user-assign.aspx?id={0}", _selectedId);
            }
            else
            {
                _ctlLinkAdd.NavigateUrl = "./org-add.aspx";
                _ctlLinkAssign.NavigateUrl = "#";
            }

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                List<Org> orgs = service.GetOrgs(null, true);
                foreach (var org in orgs)
                {
                    BindTree(_ctlTreeOrg, org);
                }
                _ctlTreeOrg.ExpandAll();
            }
        }

        #region Bind
        private void BindTree(TreeView tree, Org org)
        {
            TreeNode node = new TreeNode();
            node.Text = org.Caption;
            node.Value = org.Id.ToString("D");
            node.NavigateUrl = string.Format("./org-list.aspx?id={0}", org.Id.ToString("D"));
            if (_selectedId != Guid.Empty && org.Id == _selectedId)
            {
                node.Selected = true;
            }
            tree.Nodes.Add(node);
            foreach (var item in org.Children)
            {
                BindTree(node, item);
            }
        }

        private void BindTree(TreeNode parentNode, Org org)
        {
            TreeNode node = new TreeNode();
            node.Text = org.Caption;
            node.Value = org.Id.ToString("D");
            node.NavigateUrl = string.Format("./org-list.aspx?id={0}", org.Id.ToString("D"));
            if (_selectedId != Guid.Empty && org.Id == _selectedId)
            {
                node.Selected = true;
            }
            parentNode.ChildNodes.Add(node);

            foreach (var item in org.Children)
            {
                BindTree(node, item);
            }
        }
        #endregion
    }
}